package nus.iss.laps;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nus.iss.laps.dao.UserDAO;
import nus.iss.laps.model.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;

@Controller
public class LoginController {

	@Autowired
	private UserDAO userDAO;
	
	@RequestMapping(value= "/", method = RequestMethod.GET)
	public String home(Model model)
	{
		return "redirect:login";
	}
	
	@RequestMapping(value = "/login" , method = RequestMethod.GET)
	public String showLogin(Model model)
	{
		return "login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(Model model, WebRequest webRequest, HttpSession session, HttpServletResponse response)
	{
		String l_defaultPage = "";
		User l_user = null;
		try {
			l_user = userDAO.isExisted(webRequest.getParameter("loginid"), webRequest.getParameter("password"));
			if(l_user!= null)
			{
				l_defaultPage = l_user.getDefaultPage();
				session.setAttribute("user", l_user);
				
				if(webRequest.getParameter("remember") != null)
				{
					response.addCookie(new Cookie("laps_loginid", l_user.getLoginID()));
					response.addCookie(new Cookie("laps_password", l_user.getPassword()));
				}	
			}
		} catch (Exception ex) {
			model.addAttribute("error", ex.getMessage());
			return "error";
		}
		
		if(l_user != null)
			return "redirect:" + l_defaultPage;
		else
			return "redirect:login";
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(Model model, HttpSession session)
	{
		session.removeAttribute("user");
		return "redirect:login";
	}
}
